package com.ruoyi.operation.order.enter.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.operation.order.data.mapper.IOrderDataMapper;
import com.ruoyi.operation.order.enter.domain.EnterForm;
import com.ruoyi.operation.order.enter.mapper.IEnterFormMapper;
import com.ruoyi.operation.order.enter.service.IEnterFormService;
import com.ruoyi.operation.order.product.domain.Product;
import com.ruoyi.operation.order.product.mapper.IProductMapper;
import com.ruoyi.operation.order.shop.domain.Shop;
import com.ruoyi.operation.order.shop.mapper.IShopMapper;
import com.ruoyi.operation.order.total.domain.Total;
import com.ruoyi.operation.order.util.ExportExcelUtil;
import com.ruoyi.project.system.config.service.IConfigService;
import com.ruoyi.project.system.dept.domain.Dept;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.role.mapper.RoleMapper;
import com.ruoyi.project.system.role.service.IRoleService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.UserServiceImpl;
import net.bytebuddy.asm.Advice;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.LogicalMessage;
import java.awt.*;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author king
 * @create 2019/4/12 14:37
 */
@Service
public class EnterFormServiceImpl implements IEnterFormService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private IEnterFormMapper iEnterFormMapper;

    @Autowired
    private IConfigService configService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private RoleMapper iRoleMapper;
    @Autowired
    private IShopMapper shopMapper;
    @Autowired
    private IOrderDataMapper iOrderDataMapper;
    @Autowired
    private IProductMapper productMapper;

    /**
     * 录入订单信息
     * @param enterForm
     * @return
     */
    @Override
    public int saveEnterForm(EnterForm enterForm) {
        enterForm.setIsDel("1");
        // 默认的状态为未审核s
        enterForm.setFormStatus("1");
        enterForm.setCreateBy(ShiroUtils.getLoginId());
        // 获取好评的单价
        return iEnterFormMapper.saveEnterForm(enterForm);
    }


    /**
     * 验证订单编号是否存在
     * @param formNum
     * @return
     */
    @Override
    public String allFormNum(String formNum) {
        String formNumCount = iEnterFormMapper.allFormNum(formNum);
        if (!formNumCount.equals("0")){
            // 订单编号已经存在
            return UserConstants.FORMNUM_KEY_NOT_UNIQUE;
        }
        // 订单编号已经存在
        return UserConstants.FORMNUM_KEY_UNIQUE;
    }

    /**
     * 查询所有的订单信息
     * @param enterForm
     * @return
     */
    @Override
    public List<EnterForm> allEnterFormList(EnterForm enterForm) {
        return iEnterFormMapper.allEnterFormList(enterForm);
    }

    /**
     * 根据id获取对应的对象
     * @param id
     * @return
     */
    @Override
    public EnterForm getEnterFormById(String id) {
        return iEnterFormMapper.getEnterFormById(id);
    }

    /**
     * 编辑订单信息
     * @param enterForm
     * @return
     */
    @Override
    public int editEnterForm(EnterForm enterForm) {
        enterForm.setUpdateBy(ShiroUtils.getLoginId());
        return iEnterFormMapper.editEnterForm(enterForm);
    }

    /**
     * 删除订单信息
     * @param id
     * @return
     */
    @Override
    public int delEnterForm(String id) {
        return iEnterFormMapper.delEnterForm(id);
    }

    /**
     * 批量审核订单信息
     * @param ids
     * @return
     */
    @Override
    public int checkAllEnterForm(String ids) throws BusinessException {
        String[] idss = Convert.toStrArray(ids);
        return iEnterFormMapper.checkAllEnterForm(idss);
    }

    /**
     * 根据旺旺号查询所有的订单信息
     * @param wwNum
     * @return
     */
    @Override
    public List<EnterForm> allListEnter(String wwNum) {
        return iEnterFormMapper.allListEnter(wwNum);
    }

    @Override
    public List<EnterForm> selectByWWechat(EnterForm enterForm) {
        return iEnterFormMapper.selectByWWechat(enterForm);
    }

    @Override
    public String importEnterForm(List<EnterForm> enterFormList, Boolean isUpdateSupport) {
        if (StringUtils.isNull(enterFormList) || enterFormList.size() == 0)
        {
            throw new BusinessException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
//        String operName = ShiroUtils.getLoginName();
//        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (EnterForm enterForm : enterFormList)
        {
            try
            {
                // 验证旺旺号存在
                String countNum=iEnterFormMapper.allFormNum(enterForm.getFormNum());

//                User u = userMapper.selectUserByLoginName(user.getLoginName());
                if (Integer.parseInt(countNum) ==0)
                {
//                    enterForm.setUpdateDate();

                   enterForm.setCreateBy(ShiroUtils.getLoginId());
                   Dept dept= deptService.selectByDeptName(enterForm.getDeptName());
                   Shop shop = new Shop();
                   shop.setShopName(enterForm.getShopName());
                    List<Shop> shopList= shopMapper.allShopList(shop);
                    if(shopList.size() == 1){
                        enterForm.setEnterShopId(shopList.get(0).getId());
                    }else{
                        throw new ArithmeticException("您的店铺名称有误，请核查!");
                    }
                    if (StringUtils.isNotNull(dept))
                    {
                        enterForm.setEnterDeptId(dept.getDeptId().toString());
                    }

                   List<EnterForm> wwList = this.selectByWWechat(enterForm);
                    if(wwList.size() == 0){
                        enterForm.setFormNature("1");
                        if(iOrderDataMapper.countWwNum(enterForm.getWwNum()) > 0){
                            enterForm.setCustomerColor("2");
                        }else{
                            enterForm.setCustomerColor("1");
                        }
                    }else{
                        enterForm.setFormNature("2");
                        enterForm.setCustomerColor("0");

                    }
                    Product product = new Product();
                    product.setProductName(enterForm.getProductName());
                    product.setProductShopId(enterForm.getEnterShopId());

                    List<Product> productList = productMapper.allProductList(product);
                    if(productList.size() == 1){
                        enterForm.setEnterProductId(productList.get(0).getId());
                    }else{
                        throw new ArithmeticException("您的产品名称有误，请核查!");
                    }
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    String format = sf.format(enterForm.getOrderDate());
                    enterForm.setCreateDate(format);
//                    enterForm.setEnterDeptId(dept.getDeptId().toString());
//                    enterForm.setOrderPrice();
//                    enterForm.setCommission();
//                    enterForm.setWwNum();
//                    enterForm.setWebChatNum();
//                    enterForm.setFormNature("3");
//                    enterForm.setGoodRecord();
//                    enterForm.setFormNum();
//                    deptService.checkDeptNameUnique();
                    this.saveEnterForm(enterForm);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、订单 " + enterForm.getFormNum() + " 导入成功");
                }
//                else if (isUpdateSupport)
//                {
//                    user.setUpdateBy(operName);
//                    this.updateUser(user);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 更新成功");
//                }
                else
                {
//                    enterForm.setCreateBy(ShiroUtils.getLoginId());
//                    enterForm.setFormNature("4");
//                    this.saveEnterForm(enterForm);
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、订单 " + enterForm.getFormNum() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、订单 " + enterForm.getFormNum() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    @Override
    public void exportTotal(EnterForm enterForm, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取当前登陆人的id
        String getUserId = ShiroUtils.getLoginId();
        // 更具当前登陆人获取roleId
        List<String> getRoleId = iRoleMapper.getRoleId(getUserId);
        for (String s : getRoleId){
            if(s.equals("4")){
                // 此时是登陆人
                enterForm.setType("3");
                enterForm.setCreateBy(getUserId);
            }
        }

//        EnterForm.setUserName(getUserId);
        List<EnterForm> enterFormList = iEnterFormMapper.exportEnter(enterForm);
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFCellStyle style1 = workbook.createCellStyle(); // 样式对象

        HSSFFont font1 = workbook.createFont();         //设置红色字体
        font1.setColor(IndexedColors.RED.getIndex());
        style1.setFont(font1);                         // 把字体 应用到当前样式
//        style1.setFillForegroundColor(HSSFColor.RED.index);

        HSSFCellStyle style2 = workbook.createCellStyle(); // 样式对象
        // 生成一个字体
        HSSFFont font2 = workbook.createFont();         //设置黑体加粗

        font2.setColor(IndexedColors.VIOLET.getIndex());
        style2.setFont(font2);                        // 把字体 应用到当前样式
        // 创建导的Excel表的名字
        //sheet名
        HSSFSheet sheet = workbook.createSheet("订单统计表");
        // 设置导出文件的名字和导出的格式
        String fileName = "订单信息表"+".xls";
        String agent = request.getHeader("USER-AGENT");
        if(agent != null && agent.toLowerCase().indexOf("firefox") > 0)
        {
            fileName = "=?UTF-8?B?" + (new String(Base64Utils.encodeToString(fileName.getBytes("UTF-8")))) + "?=";
        } else {
            fileName =  java.net.URLEncoder.encode(fileName, "UTF-8");
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        // 新增数据行，设置单元格数据
        int rowNum  = 1;
        // 定义导出Excel的表格
        String[] title = {"订单编号","录单员","录入时间","平台","店铺","产品名称","订单金额","佣金","旺旺号","微信号","订单性质","好评单价","好评数","备注"};
        String[] colList = {"formNum","enterName","createDate","deptName","shopName","productName","orderPrice","commission","wwNum","webChatNum","formNature","goodPrice","goodRecord","remark"};
        HSSFRow row = sheet.createRow(0);
        // 在Excel表中添加表头
        for (int i = 0;i<title.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(title[i]);
            cell.setCellValue(text);
        }
        // 在表中存放查询到的数据到对应的列
        for (EnterForm c: enterFormList){
            HSSFRow row1 = sheet.createRow(rowNum);
            int j = 0;
            for(String s:colList){
                try {
                    HSSFCell cell = row1.createCell(j);
                    cell.setCellValue((String)getGetMethod(c, s));
                    if(c.getCustomerColor() != null){
                        if(c.getCustomerColor().equals("1")){
                            if(s.equals("wwNum")){
                                cell.setCellStyle(style1);
                            }
                        }
                        if(c.getCustomerColor().equals("2")){
                            if(s.equals("wwNum")){
                                cell.setCellStyle(style2);
                            }

                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                j++;
            }
            rowNum++;
        }
        ExportExcelUtil.outPut(response,workbook,fileName);
    }

    /**
     * 根据属性，获取get方法
     * @param ob 对象
     * @param name 属性名
     * @return
     * @throws Exception
     */
    private Object getGetMethod(Object ob , String name)throws Exception{
        Method[] m = ob.getClass().getMethods();
        for(int i = 0;i < m.length;i++){
            if(("get"+name).toLowerCase().equals(m[i].getName().toLowerCase())){
                return m[i].invoke(ob);
            }
        }
        return null;
    }


    /**
     * 批量删除录入的数据信息
     * @param ids 需要删除的数据ID
     * @return
     * @throws Exception
     */
    @Override
    public int batchDeleteIds(String ids) throws Exception {
        String[] idss = Convert.toStrArray(ids);
        return iEnterFormMapper.batchDeleteIds(idss);
    }
}
